#include "scanner.h"

#include <QMessageBox>

QByteArray Scanner::path_character = ":/List/Char/character.bin";
QByteArray Scanner::path_word[9] = {
    nullptr,
    ":/List/Word/keyword.bin",
    nullptr,
    ":/List/Word/singlechar.bin",
    ":/List/Word/doublechar.bin",
    ":/List/Word/commentbegin.bin",
    ":/List/Word/commentend.bin",
    ":/List/Word/stringdelimiter.bin",
    ":/List/Word/arraydelimiter.bin"
};

Scanner::Scanner()
{}
bool Scanner::SetFile(QByteArray fileName) {
    file.setFileName(fileName);
    if(!file.open(QIODevice::ReadOnly)) {
        QMessageBox::critical(nullptr,"错误",fileName + "文件只读方式打开失败");
        return false;
    }
    into.setDevice(&file);
    return true;
}
bool Scanner::ScanChar(QVector<Character>& data) {
    if(!SetFile(path_character)) {
        return false;
    }
    auto str = into.readAll();
    auto strList = str.split('@');
    for(int i = 0;i < strList.size();i++) {
        if(i >= _not_match) {
            break;
        }
        foreach (const auto& var, strList[i]) {
            data.push_back(Character(Character::IntToVariety(i),var.toLatin1()));
        }
    }
    file.close();
    return true;
}
bool Scanner::ScanWord(QVector<Word>& data,_variety_word kind) {
    if(path_word[kind] == nullptr || !SetFile(path_word[kind])) {
        return false;
    }
    auto str = into.readAll();
    auto strList = str.split('@');
    foreach (const auto& var, strList) {
        if(var == "" || var[0] == '\r' || var[0] == '\n') {
            continue;
        }
        data.push_back(Word(kind,var));
    }
    file.close();
    return true;
}
bool Scanner::ScanWord(QVector<Word>& data, 单词类型 kind) {
    return ScanWord(data,Word::IntToVariety(kind));
}

QString Scanner::ScanFile(QByteArray filePath) {
    if(!SetFile(filePath)) {
        return nullptr;
    }
    QString str = into.readAll();
    file.close();
    return str;
}
